import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { NpmPackageInfo } from './package-search.component';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';


export const searchUrl = 'https://npmsearch.com/query';

function createHttpOptions(packageName: string, refresh = false) {
    // npm package name search api
    // e.g., http://npmsearch.com/query?q=dom'
    const params = new HttpParams({ fromObject: { q: packageName } });
    const headerMap = refresh ? {'x-refresh': 'true'} : {};
    const headers = new HttpHeaders(headerMap) ;
    return { headers, params };
}

@Injectable()
export class PackageService {
    constructor(
        private http: HttpClient
    ) {}

    search(packageName: string, refresh = false): Observable<NpmPackageInfo[]> {
        const options = createHttpOptions(packageName, refresh);

        return this.http.get(searchUrl, options).pipe(
          map((data: any) => {
            return data.results.map(entry => ({
                name: entry.name[0],
                version: entry.version[0],
                description: entry.description[0]
              } as NpmPackageInfo )
            );
          }),
        //   catchError(this.handleError('search', []))
        );
    }

}
